package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.AnalysisVisualCatalogDTO;
import com.hunttown.mes.rpc.domain.TransportCompanyDTO;
import com.hunttown.mes.rpc.domain.TransportUserDTO;
import com.hunttown.mes.rpc.domain.enums.company.CompanyGradeEnum;
import com.hunttown.mes.rpc.domain.enums.company.CompanyScaleEnum;
import com.hunttown.mes.rpc.domain.enums.company.CompanyTypeEnum;
import com.hunttown.mes.rpc.domain.query.AnalysisVisualCatalogDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportCompanyDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * * @title: 公司管理
 * * @author: wangjunfu
 * * @date: 2019-05-25 10:36:40
 * * @description:
 */
@Controller
@RequestMapping(value = "/basic/company")
public class CompanyController {

    private final static Logger logger = LoggerFactory.getLogger(CompanyController.class);

    private final TransportCompanyManageService companyService;
    private final AnalysisManageManageService manageService;
    private final AnalysisCatalogManageService catalogService;
    private final ModelService modelService;
    private final TransportUserManageService userService;
    private final TransportOperateLogManageService logService;

    @Autowired
    public CompanyController(TransportCompanyManageService companyService, AnalysisManageManageService manageService, AnalysisCatalogManageService catalogService, ModelService modelService, TransportUserManageService userService, TransportOperateLogManageService logService) {
        this.companyService = companyService;
        this.manageService = manageService;
        this.catalogService = catalogService;
        this.modelService = modelService;
        this.userService = userService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportCompanyDTOQuery dtoQuery) {

        // 逻辑：
        // 1、取当前model_type下的一级分类10条(parent_id = 0)；
        // 2、然后依次取每条记录下面的子类，组成列表返回结果。
        if (StringUtils.isBlank(dtoQuery.getLikeName())) {
            dtoQuery.setParentId(0);    //非搜索情况下起作用
        }

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportCompanyDTO> dataPage = companyService.getForPage(dtoQuery);

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        // 依次取出每条记录的子分类
        // 这样处理的好处是：可以把每一个分类下的子分类全部取出来
        List<TransportCompanyDTO> companyList = companyService.getChildrenForEach(dataPage.getItems(), "|");

        // 实时更新列表信息
        if (companyList != null && companyList.size() > 0) {
            for (TransportCompanyDTO item : companyList) {
                item.setCatalogName(modelService.getCatalogName(item.getCatalogId()));
                item.setLinkNameCn(modelService.getUserTrueName(item.getLinkName()));
            }
        }

        model.addAttribute("companyList", companyList);
        model.addAttribute("dtoQuery", dtoQuery);

        // 显示标题
        model.addAttribute("title", CompanyTypeEnum.getEnumByKey(dtoQuery.getCompanyType()));

        // 行业
        if (dtoQuery.getCompanyType() == 1) {   //用车单位有自己的行业
            modelService.getCatalogPage(model, 15);
        } else {
            modelService.getCatalogPage(model, 7);
        }

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"G-G-GSSC"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        // 油气公司单独做一个页面
        if (dtoQuery.getCompanyType() == 6) {
            return "basic/company/index_oil";
        } else {
            return "basic/company/index";
        }
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return vm
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id, Integer companyType) {
        id = (id == null ? 0 : id);

        TransportCompanyDTO obj = new TransportCompanyDTO();
        obj.setId(id);
        obj.setCompanyGrade("B");

        if (id > 0) {
            obj = companyService.getById(id);
            if (obj != null) {
                obj.setLinkNameCn(modelService.getUserTrueName(obj.getLinkName()));
            }
        }
        model.addAttribute("Obj", obj);
        model.addAttribute("companyType", companyType);


        // 获取上级目录列表
        TransportCompanyDTOQuery query = new TransportCompanyDTOQuery();
        query.setCompanyType(companyType);
        query.setStopFlag(0);
        query.setPageSize(10000);
        Page<TransportCompanyDTO> list = companyService.getForPage(query);
        if (list != null) {
            //上面限制获取1000条记录，因此要使用这种递归方式
            model.addAttribute("childCateList", companyService.getListByRecursion(list.getItems(), 0, "|"));
        }

        // 所属行业
        AnalysisVisualCatalogDTOQuery query_industry = new AnalysisVisualCatalogDTOQuery();

        //特殊处理一下："用车单位"有自己的行业分类ModelType=15，其它公司使用通用行业ModelType=7
        if (companyType == 1) { //用车单位
            query_industry.setModelType(15);
        } else {
            query_industry.setModelType(7);
        }
        query_industry.setStopFlag(0);
        query_industry.setPageSize(1000);
        Page<AnalysisVisualCatalogDTO> list_industry = catalogService.getForPage(query_industry);
        if (list_industry != null) { //上面限制获取1000条记录，因此要使用这种递归方式
            model.addAttribute("industryCateList", catalogService.getListByRecursion(list_industry.getItems(), 0, "|"));
        }

        // 公司评级
        model.addAttribute("companyGradeList", CompanyGradeEnum.getEnumList());

        // 公司规模
        model.addAttribute("companyScaleList", CompanyScaleEnum.getEnumList());

        // 显示标题
        model.addAttribute("title", CompanyTypeEnum.getEnumByKey(companyType));

        return "basic/company/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportCompanyDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            if (objDTO.getIsSelf() == null) {
                objDTO.setIsSelf(0);
            }
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }
            if (objDTO.getLinkName() == null) {
                objDTO.setLinkName(0);
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);

                //默认值
                objDTO.setProvince(0);
                objDTO.setCity(0);
                objDTO.setZone(0);
                objDTO.setTotalRecharge(new BigDecimal(0));
                objDTO.setCurrBalance(new BigDecimal(0));

                objDTO = companyService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                //油气卡卡号可以修改
                if (objDTO.getCompanyType() != 6) {
                    objDTO.setCompanyName(null);
                }

                objDTO.setTotalRecharge(null);
                objDTO.setCurrBalance(null);

                Boolean isNext = companyService.updateInfoById(objDTO);
                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 60, objDTO.getId(), 2,
                    "更新公司信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = companyService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 60, id, 4,
                    "删除公司信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = companyService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 60, id == null ? 0 : id, 2,
                    "更新公司状态",
                    "记录状态更新" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 根据公司ID 获取联系人和联系电话

    /**
     * 根据公司ID 获取联系人和联系电话
     *
     * @param companyid 公司ID
     * @return map
     */
    @RequestMapping(value = "/getLinkPeopleAndMobile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getLinkPeople(Integer companyid) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (companyid != null && companyid > 0) {
            TransportCompanyDTO dto = companyService.getFromCacheId(companyid);

            if (dto != null) {
                map.put("returnCode", 1);
                map.put("linkName", dto.getLinkName()); //用户ID
                map.put("linkMobile", dto.getLinkMobile());
                map.put("openBack", dto.getOpenBack());
                map.put("backAccount", dto.getBackAccount());

                //linknmae存的是id, 根据id获取nickname
                TransportUserDTO userDTO = userService.getFromCacheId(dto.getLinkName());
                if (userDTO != null) {
                    map.put("linkNameCn", userDTO.getTrueName());
                }
            }
        }

        return map;
    }

    //endregion

    //region 获取当前单位的下级及下下...级部门

    /**
     * 获取当前单位的下级及下下...级部门
     *
     * @param depId       当前部门ID
     * @param companyType 单位类型： 1用车单位
     * @return map
     */
    @RequestMapping(value = "/getSubDepartment", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getSubDepartment(Integer depId, Integer companyType) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (depId == null) {
            depId = 0;
        }

        if (depId > 0) {
            TransportCompanyDTOQuery query_company = new TransportCompanyDTOQuery();
            query_company.setParentId(depId);
            query_company.setCompanyType(companyType);
            query_company.setStopFlag(0);
            query_company.setPageSize(1000);
            Page<TransportCompanyDTO> companyPage = companyService.getForPage(query_company);

            if (companyPage != null) {
                map.put("companyList", companyService.getChildrenForEach(companyPage.getItems(), "|"));
            }

            map.put("returnCode", 1);
        }

        return map;
    }

    //endregion

}